package com.shuaigef.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuaigef.springbootinit.common.BaseResponse;
import com.shuaigef.springbootinit.common.ErrorCode;
import com.shuaigef.springbootinit.common.ResultUtils;
import com.shuaigef.springbootinit.exception.BusinessException;
import com.shuaigef.springbootinit.mapper.ClassroomMapper;
import com.shuaigef.springbootinit.mapper.UserToClassMapper;
import com.shuaigef.springbootinit.model.dto.classroom.ClassroomAddRequest;
import com.shuaigef.springbootinit.model.dto.classroom.ClassroomQueryRequest;
import com.shuaigef.springbootinit.model.entity.Classroom;
import com.shuaigef.springbootinit.model.entity.User;
import com.shuaigef.springbootinit.model.entity.UserToClass;
import com.shuaigef.springbootinit.service.ClassroomService;
import com.shuaigef.springbootinit.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 班级服务实现
 */
@Service
@RequiredArgsConstructor
public class ClassroomServiceImpl extends ServiceImpl<ClassroomMapper, Classroom> implements ClassroomService {

    private final UserToClassMapper userToClassMapper;

    private final UserService userService;

    private final ClassroomMapper classroomMapper;

    /**
     * 获取当前登录学生所在的班级列表
     *
     * @return 班级列表
     */
    @Override
    public List<Classroom> getLoginStudentClassrooms() {
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 检查是否为学生
        if (loginUser.getUserRole() != 1) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非学生用户");
        }
        return this.getUserClassrooms(loginUser.getUserId());
    }

    /**
     * 获取当前登录教师管理的班级列表
     *
     * @return 班级列表
     */
    @Override
    public List<Classroom> getLoginTeacherClassrooms() {
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 检查是否为教师
        if (loginUser.getUserRole() != 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非教师用户");
        }
        return this.getUserClassrooms(loginUser.getUserId());
    }

    /**
     * 获取用户所在的班级列表
     *
     * @param userId 学生ID
     * @return 班级列表
     */
    @Override
    public List<Classroom> getUserClassrooms(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询用户-班级关联表
        List<UserToClass> userToClasses = userToClassMapper.selectList(new LambdaQueryWrapper<UserToClass>()
                .eq(UserToClass::getUserId, userId));

        if (userToClasses.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取班级ID列表
        List<Integer> classroomIds = userToClasses.stream()
                .map(UserToClass::getClassroomId)
                .collect(Collectors.toList());

        // 查询班级信息
        return classroomMapper.selectBatchIds(classroomIds);
    }


    /**
     * 根据条件查询班级
     *
     * @param classroomQueryRequest 查询条件
     * @return 班级列表
     */
    @Override
    public List<Classroom> queryClassrooms(ClassroomQueryRequest classroomQueryRequest) {
        if (classroomQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<Classroom> queryWrapper = new LambdaQueryWrapper<>();
        if (classroomQueryRequest.getClassroomId() != null) {
            queryWrapper.eq(Classroom::getClassroomId, classroomQueryRequest.getClassroomId());
        }
        if (classroomQueryRequest.getClassroomName() != null) {
            queryWrapper.like(Classroom::getClassroomName, classroomQueryRequest.getClassroomName());
        }
        return classroomMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID获取班级信息
     *
     * @param id 班级ID
     * @return 班级信息
     */
    @Override
    public Classroom getClassroomById(Integer id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Classroom classroom = classroomMapper.selectById(id);
        if (classroom == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return classroom;
    }

    /**
     * 新建班级
     *
     * @param classroomAddRequest 新建班级请求
     * @return 新建的班级ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Void> createClassroom(ClassroomAddRequest classroomAddRequest) {
        if (classroomAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取当前登录用户 必须是教师
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (loginUser.getUserRole() != 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "非教师用户");
        }

        // 校验班级名称
        String classroomName = classroomAddRequest.getClassroomName();
        if (StringUtils.isBlank(classroomName)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级名称不能为空");
        }
        if (classroomName.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级名称过长");
        }

        // 创建班级
        Classroom classroom = Classroom.builder()
                .classroomName(classroomAddRequest.getClassroomName())
                .build();

        // 保存班级信息
        int rows = classroomMapper.insert(classroom);
        if (rows <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建班级失败");
        }

        // 创建教师和班级的关联关系
        UserToClass userToClass =  UserToClass.builder()
                .userId(loginUser.getUserId())
                .classroomId(classroom.getClassroomId())
                .build();
        rows = userToClassMapper.insert(userToClass);
        if (rows <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建班级关联关系失败");
        }

        return ResultUtils.success();
    }
}




